package io.terminus.lego.shinda.web.controller

import io.swagger.annotations.Api
import io.terminus.lego.shinda.web.cache.RedisCacheManager
import io.terminus.lego.shinda.web.controller.dto.BasicPhone
import io.terminus.lego.shinda.web.controller.dto.SignUpEmail
import io.terminus.lego.shinda.web.controller.dto.SignUpPhone
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.codec.ServerSentEvent
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Flux
import reactor.util.function.Tuple2
import reactor.util.function.Tuples
import java.time.Duration
import java.util.concurrent.ThreadLocalRandom

/**
 * @author wangmeng
 * @date 2018/4/12
 */
@Api("注册服务")
@RestController
@RequestMapping("api/sign-up/")
class SignUpController @Autowired constructor(val redisCacheManager: RedisCacheManager) {
    val log = LoggerFactory.getLogger(javaClass)

    @PostMapping("/email")
    fun byEmail(signUp: SignUpEmail): String {
        //TODO 发送激活邮件
        return "success"
    }

    @PostMapping("/phone")
    fun byPhone(signUp: SignUpPhone): String {
        //TODO 手机注册、验证短信验证码
        return "success"
    }

    @PostMapping("/phone/captcha")
    fun sendCaptcha(phone: BasicPhone): String {
        //TODO 发送手机验证码
        return "success"
    }

    @GetMapping("/randomNumbers")
    fun randomNumbers(): Flux<ServerSentEvent<Int>> {
        return Flux.interval(Duration.ofSeconds(1))
                .map<Tuple2<Long, Int>> { seq -> Tuples.of(seq!!, ThreadLocalRandom.current().nextInt()) }
                .map { data ->
                    ServerSentEvent.builder<Int>()
                            .event("random")
                            .id(java.lang.Long.toString(data.getT1()))
                            .data(data.getT2())
                            .build()
                }
    }


}